import Snake from './Snake';
import Food from './Food';
import ScorePanel from './ScorePanel'
class GameControl{
    //蛇
    snake:Snake;
    //食物
    food:Food;
    //积分器
    scorePanel:ScorePanel;

    //创建一个属性来存储蛇的移动方向（也就是按键的方向）
    direction:string='';
    isLive:boolean=true;

    constructor(){
        this.snake=new Snake();
        this.food=new Food();
        this.scorePanel = new ScorePanel();

        this.init()
    }

    init(){
        document.addEventListener('keydown',this.keydownHandler.bind(this));
        this.run();
    };
    keydownHandler(event: KeyboardEvent){
        console.log(event.key)
        this.direction=event.key
    };
    /**   keyCode
     * up  38
     * dowm 40
     * left 37
     * right 39
     */

    run(){
       // 获取蛇现在坐标
       let X = this.snake.X;
       let Y = this.snake.Y;
      // 根据按键方向来计算X值和Y值（未更新）
      switch (this.direction) {
        case "ArrowUp":
        case "Up":
            // 向上移动 top 减少
            Y -= 10;
            break;
        case "ArrowDown":
        case "Down":
            // 向下移动 top 增加
            Y += 10;
            break;
        case "ArrowLeft":
        case "Left":
            // 向左移动 left 减少
            X -= 10;
            break;
        case "ArrowRight":
        case "Right":
            // 向右移动 left 增加
            X += 10;
            break;
    }
      //监视是否吃到食物
      this.cheakEat(X,Y)

         //修改蛇的X和Y值
         try {
            this.snake.X = X;
            this.snake.Y = Y;
        } catch (e) {
            // 进入到catch，说明出现了异常，游戏结束，弹出一个提示信息
            alert(e.message + ' GAME OVER!');
            // 将isLive设置为false
            this.isLive = false;
        }
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30);
    }
     //是否吃到食物
    cheakEat(X:number,Y:number){
          if(X===this.food.X&&Y===this.food.Y){
              console.log('吃到了')
              this.scorePanel.addScore();
              this.food.change();
              this.snake.addBody();
          }
    }
}
export default GameControl;